import os
from data.base_dataset import BaseDataset, get_transform
from data.image_folder import make_dataset
from PIL import Image
import random


class UnalignedDataset(BaseDataset):
    """
    This dataset class can load unaligned/unpaired datasets.

    It requires two directories to host training images from domain A '/path/to/data/trainA'
    and from domain B '/path/to/data/trainB' respectively.
    You can train the model with the dataset flag '--dataroot /path/to/data'.
    Similarly, you need to prepare two directories:
    '/path/to/data/testA' and '/path/to/data/testB' during test time.
    """

    def __init__(self, opt):
        """Initialize this dataset class.

        Parameters:
            opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
        """
        BaseDataset.__init__(self, opt)
        if opt.netG != 'resnet_6blocks_sr':
            self.dir_A = os.path.join(opt.dataroot, opt.phase + 'A')  # create a path '/path/to/data/trainA'
            self.dir_B = os.path.join(opt.dataroot, opt.phase + 'B')  # create a path '/path/to/data/trainB'

            self.A_paths = sorted(make_dataset(self.dir_A, opt.max_dataset_size))   # load images from '/path/to/data/trainA'
            self.B_paths = sorted(make_dataset(self.dir_B, opt.max_dataset_size))    # load images from '/path/to/data/trainB'
            self.A_size = len(self.A_paths)  # get the size of dataset A
            self.B_size = len(self.B_paths)  # get the size of dataset B
            btoA = self.opt.direction == 'BtoA'
            input_nc = self.opt.output_nc if btoA else self.opt.input_nc       # get the number of channels of input image
            output_nc = self.opt.input_nc if btoA else self.opt.output_nc      # get the number of channels of output image
            self.transform_A = get_transform(self.opt, grayscale=(input_nc == 1))
            self.transform_B = get_transform(self.opt, grayscale=(output_nc == 1))
            self.sr = False
        else:
            self.dir_A = os.path.join(opt.dataroot, opt.phase + 'A')  # create a path '/path/to/data/trainA'
            self.dir_B = os.path.join(opt.dataroot, opt.phase + 'B')  # create a path '/path/to/data/trainB'
            self.dir_A_32 = os.path.join(opt.dataroot, opt.phase + 'A_32')  # create a path '/path/to/data/trainA_32'
            self.dir_B_32 = os.path.join(opt.dataroot, opt.phase + 'B_32')  # create a path '/path/to/data/trainB_32'
            self.dir_A_64 = os.path.join(opt.dataroot, opt.phase + 'A_64')  # create a path '/path/to/data/trainA_32'
            self.dir_B_64 = os.path.join(opt.dataroot, opt.phase + 'B_64')  # create a path '/path/to/data/trainB_32'

            self.A_paths = sorted(make_dataset(self.dir_A, opt.max_dataset_size))   # load images from '/path/to/data/trainA'
            self.B_paths = sorted(make_dataset(self.dir_B, opt.max_dataset_size))    # load images from '/path/to/data/trainB'
            self.A_paths_32 = sorted(make_dataset(self.dir_A_32, opt.max_dataset_size))   # load images from '/path/to/data/trainA_32'
            self.B_paths_32 = sorted(make_dataset(self.dir_B_32, opt.max_dataset_size))    # load images from '/path/to/data/trainB_32'
            self.A_paths_64 = sorted(make_dataset(self.dir_A_64, opt.max_dataset_size))   # load images from '/path/to/data/trainA_64'
            self.B_paths_64 = sorted(make_dataset(self.dir_B_64, opt.max_dataset_size))    # load images from '/path/to/data/trainB_64'
            self.A_size = len(self.A_paths)  # get the size of dataset A
            self.B_size = len(self.B_paths)  # get the size of dataset B
            btoA = self.opt.direction == 'BtoA'
            input_nc = self.opt.output_nc if btoA else self.opt.input_nc       # get the number of channels of input image
            output_nc = self.opt.input_nc if btoA else self.opt.output_nc      # get the number of channels of output image
            self.transform_A = get_transform(self.opt, grayscale=(input_nc == 1))
            self.transform_B = get_transform(self.opt, grayscale=(output_nc == 1))
            self.sr = True

    def __getitem__(self, index):
        """Return a data point and its metadata information.

        Parameters:
            index (int)      -- a random integer for data indexing

        Returns a dictionary that contains A, B, A_paths and B_paths
            A (tensor)       -- an image in the input domain
            B (tensor)       -- its corresponding image in the target domain
            A_paths (str)    -- image paths
            B_paths (str)    -- image paths
        """
        if self.sr == False:
            A_path = self.A_paths[index % self.A_size]  # make sure index is within then range
            if self.opt.serial_batches:   # make sure index is within then range
                index_B = index % self.B_size
            else:   # randomize the index for domain B to avoid fixed pairs.
                index_B = random.randint(0, self.B_size - 1)
            B_path = self.B_paths[index_B]
            A_img = Image.open(A_path).convert('RGB')
            B_img = Image.open(B_path).convert('RGB')
            # apply image transformation
            A = self.transform_A(A_img)
            B = self.transform_B(B_img)

            return {'A': A, 'B': B, 'A_paths': A_path, 'B_paths': B_path}
        else:
            index_A = index % self.A_size
            A_path = self.A_paths[index_A]  # make sure index is within then range
            A_path_32 = self.A_paths_32[index_A]  # make sure index is within then range
            A_path_64 = self.A_paths_64[index_A]  # make sure index is within then range
            if self.opt.serial_batches:  # make sure index is within then range
                index_B = index % self.B_size
            else:  # randomize the index for domain B to avoid fixed pairs.
                index_B = random.randint(0, self.B_size - 1)
            B_path = self.B_paths[index_B]
            B_path_32 = self.B_paths_32[index_B]
            B_path_64 = self.B_paths_64[index_B]
            A_img = Image.open(A_path).convert('RGB')
            A_img_32 = Image.open(A_path_32).convert('RGB')
            A_img_64 = Image.open(A_path_64).convert('RGB')
            B_img = Image.open(B_path).convert('RGB')
            B_img_32 = Image.open(B_path_32).convert('RGB')
            B_img_64 = Image.open(B_path_64).convert('RGB')
            # apply image transformation
            A = self.transform_A(A_img)
            B = self.transform_B(B_img)
            A_32 = self.transform_A(A_img_32)
            B_32 = self.transform_B(B_img_32)
            A_64 = self.transform_A(A_img_64)
            B_64 = self.transform_B(B_img_64)
            return {'A': A, 'B': B, 'A_paths': A_path, 'B_paths': B_path,\
                    'A_32': A_32, 'B_32': B_32, 'A_paths_32': A_path_32, 'B_paths_32': B_path_32,\
                    'A_64': A_64, 'B_64': B_64, 'A_paths_64': A_path_64, 'B_paths_64': B_path_64}

    def __len__(self):
        """Return the total number of images in the dataset.

        As we have two datasets with potentially different number of images,
        we take a maximum of
        """
        return max(self.A_size, self.B_size)
